#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mqtt_file_transfer.h"
#include "connection/mqtt_client.h"

// 进度回调
void progress_callback(const char *file_id, int chunk_index, int total_chunks) {
    printf("Progress: %s - %d/%d\n", file_id, chunk_index, total_chunks);
}

// 完成回调
void complete_callback(const char *file_id, int status, const char *message) {
    printf("Complete: %s - %d (%s)\n", file_id, status, message);
}

int main(int argc, char *argv[]) {
    if (argc < 4) {
        printf("Usage: %s <send|receive> <broker> <port> [filename|path]\n", argv[0]);
        return 1;
    }

    const char *mode = argv[1];
    const char *broker = argv[2];
    int port = atoi(argv[3]);

    // 创建传输上下文
    file_transfer_ctx_t *ctx = file_transfer_create(broker, port, DEFAULT_CLIENT_ID);
    if (!ctx) {
        printf("Failed to create transfer context\n");
        return 1;
    }

    // 设置回调
    file_transfer_set_callbacks(ctx, progress_callback, complete_callback, NULL);

    if (strcmp(mode, "send") == 0) {
        if (argc < 5) {
            printf("Send mode requires filename\n");
            file_transfer_destroy(ctx);
            return 1;
        }

        const char *filename = argv[4];
        if (file_transfer_send(ctx, filename) != 0) {
            printf("Failed to send file\n");
            file_transfer_destroy(ctx);
            return 1;
        }

        printf("Sending file: %s\n", filename);
    } else if (strcmp(mode, "receive") == 0) {
        const char *save_path = argc >= 5 ? argv[4] : ".";
        if (file_transfer_receive(ctx, save_path) != 0) {
            printf("Failed to start receiver\n");
            file_transfer_destroy(ctx);
            return 1;
        }

        printf("Receiving files to: %s\n", save_path);
    } else {
        printf("Invalid mode: %s\n", mode);
        file_transfer_destroy(ctx);
        return 1;
    }

    // 主循环
    while (1) {
        sleep(1);
    }

    file_transfer_destroy(ctx);
    return 0;
}
